﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common;
using Provider;
using System.Data;


namespace AccessToDataEnergyLibrury
{

    public partial class AccessDataEnergyLibrury
    {
    /// <summary>
        /// Метод возвращает все документы из таблицы Documentation и связаных таблиц
        /// </summary>
        /// <returns></returns>
        public List<Documentation> GetAllDocuments()
        {
            DataRowCollection searchedRow = this.energyDataSet.documentation.Rows;
            //DataRow[] searchedRow = this.energyDataSet.documentation.Select();
            return this.GetRestPartsOfDocumentation(searchedRow);
        }
    /// <summary>
        ///Метод GetRestPartsOfDocumentation принимающий параметр типа DataRow
        /// </summary>
        /// <param name="searchedRows"></param>
        /// <returns></returns>
        List<Documentation> GetRestPartsOfDocumentation(DataRow[] searchedRows)
        {
            if (searchedRows == null || searchedRows.Length == 0)
                return null;
            List<Documentation> documentations = new List<Documentation>();

            foreach (energyzmemDataSet.documentationRow documentationRow in searchedRows)
            {
                Documentation document = new Documentation();
                document.ISBN = documentationRow.number_documents.ToString();
                document.Date_1 = documentationRow.data1;
                document.Date_2 = documentationRow.data2;
                document.Information = documentationRow.Information;
                

                DataRow[] ItemsRows = this.energyDataSet.itmes.Select("id_Item = " + documentationRow.itmesRow.id_Item);

                if (ItemsRows != null && ItemsRows.Length != 0)
                {
                    energyzmemDataSet.itmesRow itemRow = (energyzmemDataSet.itmesRow)ItemsRows[0];
                    document.ID = documentationRow.itmesRow.id_Item;
                    document.Name = documentationRow.itmesRow.name_item;
                    document.PublishedDate = documentationRow.itmesRow.publisher_date_item.Date;
                }
                 else
                {
                   throw new Exception("Нет данных в таблице Items для документов");
                }

                    if (documentationRow.authorsRow != null)
                    {
                        document.AuthorName = documentationRow.authorsRow.employeeRow.name;
                        //document.AuthorName = documentationRow.authorsRow.employeeRow.last_name;

                    }
                    else
                    {
                        throw new Exception("Нет данных в таблице Authors для документов");
                    }

                    if (documentationRow.itmesRow.enterpriseRow.id_enterprise.ToString() != null)
                 {
                     document.Publisher = documentationRow.itmesRow.enterpriseRow.name_company;
                 }
                 else
                 {
                     throw new Exception("Нет данных в таблице Enterprise для документов");
                 }

                    if (documentationRow.employeeRow != null)
                    {
                        document.Approved = documentationRow.employeeRow.last_name;
                    }
                    else
                    {
                        throw new Exception("Нет данных в таблице Employee для документов");
                    }
                        if (documentationRow.ref_documentsRow != null)
                        {
                            document.TypeDocument = documentationRow.ref_documentsRow.Documents_Name;
                        }
                        else
                        {
                            throw new Exception("Нет данных в таблице ref_documents для документов");
                        }
                    documentations.Add(document);
                }
                return documentations;
            }
    /// <summary>
        /// Метод извлекает из связаных таблиц недостающие данные для колекции строк из таблицы Documentation
        /// </summary>
        /// <param name="searchedRows"></param>
        /// <returns></returns>
        List<Documentation> GetRestPartsOfDocumentation(DataRowCollection searchedRows)
        {
            if (searchedRows == null || searchedRows.Count == 0)
            {
                return null;
            }
            else
            {
                List<Documentation> documentations = new List<Documentation>();

                foreach (energyzmemDataSet.documentationRow documentationRow in searchedRows)
                {
                    Documentation document = new Documentation();
                    document.ISBN = documentationRow.number_documents.ToString();
                    document.Date_1 = documentationRow.data1;
                    document.Date_2 = documentationRow.data2;
                    document.Information = documentationRow.Information;
                    

                    if (documentationRow.itmesRow != null)
                    {
                        document.ID = documentationRow.itmesRow.id_Item;
                        document.Name = documentationRow.itmesRow.name_item;
                        document.PublishedDate = documentationRow.itmesRow.publisher_date_item.Date;
                    }
                    else
                    {
                        throw new Exception("Нет данных в таблице Items для документов");
                    }

                        if (documentationRow.authorsRow != null)
                        {
                            document.AuthorName = documentationRow.authorsRow.employeeRow.last_name + " " + documentationRow.authorsRow.employeeRow.name + " " + documentationRow.authorsRow.employeeRow.patronymic;                            
                        }
                        else
                        {
                            throw new Exception("Нет данных в таблице Authors для документов");
                        }

                    if (documentationRow.employeeRow != null)
                    {
                        document.Approved = documentationRow.employeeRow.last_name + " " + documentationRow.employeeRow.name + " " + documentationRow.employeeRow.patronymic;
                    }
                    else
                    {
                        throw new Exception("Нет данных в таблице Employee для документов");
                        
                    }

                        if (documentationRow.itmesRow != null)
                        {
                            document.Publisher = documentationRow.itmesRow.enterpriseRow.abbreviation;
                        }
                        else
                        {
                            throw new Exception("Нет данных в таблице Enterprise для документов");
                        }

                    if (documentationRow.resourcesRow != null)
                    {
                        document.Resourcse = documentationRow.resourcesRow.nom_num;
                    }
                    else
                    {
                        throw new Exception("Нет данных в таблице Resourse для документов");
                    }

                        if (documentationRow.ref_documentsRow != null)
                        {
                            document.TypeDocument = documentationRow.ref_documentsRow.Documents_Name;
                        }
                        else
                        {
                            throw new Exception("Нет данных в таблице ref_documents для документов");
                        }
                    documentations.Add(document);
                }
                return documentations;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="searchedDocumentation"></param>
        /// <returns></returns>
        public  List<Documentation> GetSearchedDocuments(Documentation searchedDocumentation)
        {
            //получаем набор найденных строк из таблицы Items
            energyzmemDataSet.itmesRow[] searchedItemsRows = 
                (energyzmemDataSet.itmesRow[])energyDataSet.itmes.Select(MakeFilteredQwery(searchedDocumentation.ItemFields));

            //получаем набор найденных строк из таблицы Authors
            energyzmemDataSet.authorsRow[] searchedAuthorsRows = 
                (energyzmemDataSet.authorsRow[])energyDataSet.authors.Select(MakeFilteredQwery(searchedDocumentation.AuthorFields));
 
            if (
                (searchedItemsRows == null || searchedItemsRows.Length == 0) ||
                (searchedAuthorsRows == null || searchedAuthorsRows.Length == 0) //||
                //(searchedPublisheRows == null || searchedPublisheRows.Length == 0)
              )

                return new List<Documentation>(0);

            //создаем списки для набора строк Items, Enterprise и Authors для более 
            //гибкого манипулирования масива

            List<energyzmemDataSet.itmesRow> searchedItemsRowsList =
                searchedItemsRows.ToList<energyzmemDataSet.itmesRow>();

            List<energyzmemDataSet.documentationRow> searchedDocumentsRowsList = new List<energyzmemDataSet.documentationRow>();

            //заполняем список книг. Для каждой записи в таблице Items 
            //существует всего одна запись в таблице Documentation

            foreach (energyzmemDataSet.itmesRow itemRow in searchedItemsRowsList)
            {
             energyzmemDataSet.documentationRow[] documentsRow = itemRow.GetdocumentationRows();
             if (documentsRow != null && documentsRow.Length != 0)
                 searchedDocumentsRowsList.Add(documentsRow[0]);
            }

            // конечный набор искомых строк
            List<energyzmemDataSet.documentationRow> realDocumentationsRows =
                new List<energyzmemDataSet.documentationRow>();
            //выбираем те книги, которые
            for (int i = 0; i < searchedAuthorsRows.Length; i++)
            {
                List<energyzmemDataSet.documentationRow> tempSearched =
                    searchedDocumentsRowsList.FindAll(val => val.FK_ID_Employee_Autor == searchedAuthorsRows[i].FK_ID_Employee_Authors);

                realDocumentationsRows.AddRange(tempSearched);
            }
            if (realDocumentationsRows.Count == 0)
                return new List<Documentation>(0);
            return GetRestPartsOfDocumentation(realDocumentationsRows.ToArray());
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="Document_"></param>
        public void AddDocument(List<Documentation>Document_)
        {
            //DataRow authorDataRow;
            //DataRow enterpriseDataRow;
            //DataRow itemsDataRow;
            //DataRow employeeDataRow;
            //DataRow resourcesDataRow;
            //DataRow ref_documentsDataRow;





            //foreach (Documentation document in Document_)
            //{
            //    bool canAdd = IsUniqueBookInDb(document, out authorDataRow );
            //    if (!canAdd)
            //        continue;

            //        energyzmemDataSet.enterpriseRow enterpriseRow;
            //        //Если еще нету издательства в БД
            //        if(enterpriseDataRow == null)
            //        {
            //            enterpriseRow = energyDataSet.enterprise.AddenterpriseRow;
            //        }
            //            else
            //        {
            //            enterpriseRow = (energyzmemDataSet.enterpriseRow)enterpriseDataRow;
            //        }

            //    energyzmemDataSet.itmesRow itemsRow;
            //    //Если еще нету 
            //    if(itemsDataRow == null)
            //    {
            //        energyDataSet.itmes.AdditmesRow(document.ID, document.Name,enterpriseRow, document.PublishedDate);
            //    }

            //        energyzmemDataSet.authorsRow authorsRow;
            //        //
            //        if(authorDataRow == null)
            //        {

            //        }
            //            else
            //        {
            //            authorsRow = (energyzmemDataSet.authorsRow)authorDataRow;
            //        }

            //    energyzmemDataSet.employeeRow employeeRow;
            //    //
            //    if(employeeDataRow==null)
            //    {

            //    }
            //        else
            //    {
            //        employeeRow = (energyzmemDataSet.employeeRow)employeeDataRow;
            //    }

            //        energyzmemDataSet.resourcesRow resourcesRow;
            //        //
            //        if(resourcesDataRow == null)
            //        {

            //        }
            //            else
            //        {
            //            resourcesRow = (energyzmemDataSet.resourcesRow)resourcesDataRow;
            //        }

            //    energyzmemDataSet.ref_documentsRow ref_documentsRow;
            //    //
            //    if(ref_documentsDataRow == null)
            //    {

            //    }
            //        else
            //    {
            //        ref_documentsRow = (energyzmemDataSet.ref_documentsRow)ref_documentsDataRow;
            //    }

            //    energyDataSet.documentation.AdddocumentationRow(itemsRow, document.ISBN, authorsRow,ref_documentsRow,resourcesRow,document.Date_1, document.Date_2,
            //}
        }


        private bool IsUniqueBookInDb(Documentation document, out DataRow authorDataRow)
        {
            DataRow[] documentRows = energyDataSet.documentation.Select("[number_documents] = '" + document.ISBN + "'");

                authorDataRow = null;
            if (documentRows != null && documentRows.Length > 0)

                return false;

            DataRow[] authorsRows = energyDataSet.authors.Select("[FK_ID_Employee_Authors] = '" + document.AuthorName + "'");

            if (authorsRows != null && authorsRows.Length > 0)
            {
                authorDataRow = authorsRows[0];

                foreach (DataRow authorR in authorsRows)
                {
                    energyzmemDataSet.documentationRow[] documentsRow = ((energyzmemDataSet.authorsRow)authorR).GetdocumentationRows();

                    foreach (energyzmemDataSet.documentationRow bookR in documentsRow)
                    {
                        if (document.Name == bookR.itmesRow.name_item)
                        {
                            return false;
                        }
                    }
                }
            }   
            return true;        
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="documentID"></param>
        /// <param name="documentName"></param>
        /// <returns></returns>
      public List<Copies> GetBookCopies(int documentID)
        {
            DataRow[] bookCopies = energyDataSet.copies.Select("FK_id_item = '"+ documentID + "'");
            //documentName = energyDataSet.itmes.FindByid_Item(documentID).name_item;

            List<Copies> copies = new List<Copies>();
            
            foreach(energyzmemDataSet.copiesRow singleCop in bookCopies  )
            {
                bool IsBoroowed = false;
               //DataRow borrowed = energyDataSet.borrows.Rows.Find(singleCop.id_copies);
               //DataRow[] borrowed = singleCop.GetborrowsRows();
                DataRow[] borrowed = singleCop.GetChildRows("FK_Borrows_Copies_id_copies");
                if (borrowed != null && borrowed.Length > 0)
                {
                    IsBoroowed = true;
                }
                copies.Add(new Copies(singleCop.id_copies, singleCop.FK_id_item, IsBoroowed));
            }
            return copies;
        }
        public bool BorrowingDocumemt(int copieID)
        {
            return true;
        }

        public List<Documentation> GetBookBook1(int documentID)
        {
            DataRow[] bookCopies = energyDataSet.documentation.Select("FK_ID_Item_Documentation = '" + documentID + "'");
            List<Documentation> book1 =  new List<Documentation>();
            foreach (energyzmemDataSet.documentationRow docRow in bookCopies)
            {
                //DataRow[] bocChild = docRow.GetParentRows("FK_id_documents");
                book1.Add(new Documentation());
            }
            
            return book1;
        }

        public List<Documentation> GetBookBook2(int documentID)
        {
            DataRow[] bookCopies = energyDataSet.documentation.Select("FK_ID_Item_Documentation = '" + documentID + "'");
            
            List<Documentation> book = new List<Documentation>();
            foreach (energyzmemDataSet.documentationRow docRow in bookCopies)
            {
                DataRow[] bocChild = docRow.GetChildRows("FK_ID_Item_Documentation");
                book.Add(new Documentation());
            }

            return book;
        }
    }
     
}
